<?php

use OSS\OssClient;

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(6);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

$icon = $DB->get('game_icon','*');
if($action == 'upload') {
    checkFunc(6, '权限不足，无法操作');

    try {
        $ossclient = new OssClient($akid, $aksec, $endpoint);
        $bucket = 'kdwawajistatic';
        $name_arr = explode('.', $_FILES['file']['name']);
        $fext = $name_arr[count($name_arr)-1];
        $file_name = 'icon_' . date('YmdHis').'_'.mt_rand(100000,999999).'.'.$fext;
        $object = 'damai/lyfen/bannerUpload/' . $file_name;
        $filePath = $_FILES['file']['tmp_name'];
        $ossclient->uploadFile($bucket, $object, $filePath);
    } catch(\Exception $e) {
        echo 'BAD|上传OSS文件失败';
        exit;
    }
    echo 'OK|'.$file_name;
    exit;
}
else if($action == 'edit') {
    checkFunc(6, '权限不足，无法操作');
    $filename = $_GET['oss_filename'] ?? '';
    $data = ['icon_url' => $CDN_URL . '/bannerUpload/'.$filename,'create_time' => $now];
    $icon = $DB->get('game_icon','*');
    if ($icon){
        $res = $DB->update('game_icon',$data);
    }else{
        $DB->insert('game_icon', $data);
    }
    operate_log('icon', 'edit_icon', ['配置url'=>$CDN_URL . '/bannerUpload/' . $filename,]);
    goExit('game_icon.php?success=配置修改成功!');
}

display_header();
?>
<link href="css/jquery.dm-uploader.min.css" rel="stylesheet">
<style>
    .valid_task {background:#ffe; /* #C2ECA7 */;}
    #fileinp{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }
</style>

<section class="content">

    <?php display_title('icon配置'); ?>

    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-warning">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-tasks"></i> icon配置</h3>
        </div>
        <div class="box-body">
            <table id="logtable" class="table table-bordered table-striped dataTable table-hover table-condensed" role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="center" width="230">icon</th>
                    <th class="center" width="300">icon路径</th>
                    <th class="center" width="300">更新时间</th>
                    <th class="center">上传</th>
                    <th class="center">操作</th>
                </tr>
                </thead>
                <tbody>
                    <tr role="row" style="height:38px;text-align:center;">
                        <td class="cname"> <img src="<?php echo $icon['icon_url']; ?>" height="60" /></td>
                        <td class="address"><?php echo $icon['icon_url']; ?></td>
                        <td class="time"><?php echo $icon ? date('Y-m-d H:i:s',$icon['create_time']) : ''; ?></td>
                        <td class="cdesc">
                            <div id="drop-area" style="float:left; padding-top:40px; margin-left:20px;">
                                <label for="fileinp">
                                    <span id="text" style="padding:10px 20px;border-radius:4px;background:#007bff;color:#fff;">请上传图片</span>
                                    <input type="file" id="fileinp" />
                                    <br />
                                    <div style="margin-top:15px;font-size:12px;font-weight:normal;" id="upload_result"></div>
                                    <input type="hidden" id="oss_filename" name="oss_filename" value="" />
                                </label>
                            </div>
                        </td>
                        <td class="left" style="padding:0;padding-left:15px;" >
                            <button  class="btn btn-primary btn-sm edit_icon">确认修改</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- SlimScroll -->
<script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<script src="js/jquery.dm-uploader.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#drop-area").dmUploader({
            url: 'game_icon.php?action=upload',
            multiple: false,
            maxFileSize: 3000000,
            allowedTypes: 'image/*',
            extFilter: ['jpg','jpeg','png','gif'],
            onInit: function(){
                console.log('Callback: Plugin initialized');
            },
            onNewFile: function(id, file){
                // When a new file is added using the file selector or the DnD area
                console.log('New file added #' + id);
                if (typeof FileReader !== "undefined"){
                    var reader = new FileReader();
                    var img = $('#avatar_preview');
                    reader.onload = function (e) {
                        img.attr('src', e.target.result);
                    }
                    reader.readAsDataURL(file);
                }
            },
            onBeforeUpload: function(id){
                console.log('start upload ... ' + id);
            },
            onUploadProgress: function(id, percent){
                console.log(id + ' uploading ... ' + percent);
            },
            onUploadSuccess: function(id, data){
                var darr = data.split('|');
                if(darr[0] != 'OK') {
                    alert('图片上传失败，请联系管理员');
                } else {
                    $('#upload_result').text('图片上传成功，文件名：' + darr[1]);
                    $('#oss_filename').val(darr[1]);
                }
            },
            onUploadError: function(id, xhr, status, message){
                alert('图片上传失败，请联系管理员');
            },
            onFileSizeError: function(file){
                alert('图片不可超过3M');
            },
            onFileTypeError: function(file){
                alert('图片类型错误');
            },
            onFileExtError: function(file){
                alert('图片扩展名错误');
            }
        });

        $('.edit_icon').click(function() {
            var _filename = $('#oss_filename').val();
            if(!_filename) {
                alert('图片未上传');
                return false;
            }
            location.href = 'game_icon.php?action=edit&oss_filename=' + _filename;
        });
        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });
</script>

</body>
</html>
